package com.gun3y.factory;

import java.util.Locale;
import java.util.Properties;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.htmlparser.Parser;
import org.htmlparser.PrototypicalNodeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gun3y.entity.htmlparser.CustomizedTag;
import com.gun3y.utils.ResourceLoader;

@Component
public class ParserFactory {

    @Autowired
    private ResourceLoader resourceLoader;

    private PrototypicalNodeFactory nodeFactory;

    @PostConstruct
    public void init() {
	nodeFactory = new PrototypicalNodeFactory();

	Properties tags = resourceLoader.getTagProperties();

	if (tags != null) {

	    Set<?> registeredTags = nodeFactory.getTagNames();

	    for (Object tag : tags.keySet()) {
		String tagName = tag.toString().toUpperCase(Locale.ENGLISH);

		if (!registeredTags.contains(tagName)) {
		    nodeFactory.registerTag(new CustomizedTag(tagName));
		}
	    }
	}
    }

    public Parser createParser(String html, String encoding) {
	Parser parser = Parser.createParser(html, encoding);
	parser.setNodeFactory(this.nodeFactory);
	return parser;
    }

}
